package com.leyantech.ecp.agenx.common.utils;

import com.linkedin.urls.Url;
import com.linkedin.urls.detection.UrlDetector;
import com.linkedin.urls.detection.UrlDetectorOptions;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;

import java.util.List;
import java.util.Optional;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-12-20.
 */
@Slf4j
public final class UrlUtils {

  /**
   * 解析包含 url 串的 query, 只解析第一个 url.
   */
  public static Optional<HttpUrl> extractUrl(String content) {
    final List<Url> urls = new UrlDetector(content, UrlDetectorOptions.Default).detect();
    if (urls.isEmpty()) {
      return Optional.empty();
    }

    final Url url = urls.get(0);
    final HttpUrl httpUrl = HttpUrl.parse(url.getFullUrlWithoutFragment());
    return Optional.ofNullable(httpUrl);
  }

}
